package io.renren.modules.app.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.entity.OrderEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.PayOrderform;
import io.renren.modules.app.form.UpdateNativeOrderStatusForm;
import io.renren.modules.app.service.OrderSeervice;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/app/zfb")
@Api("支付宝业务接口")
public class ZFBController {
    @Value("${alipay.app.app-id}")
    private String app_appId;
    @Value("${alipay.app.public-key}")
    private String app_publicKey;
    @Value("$alipay.app.private-key}")
    private String app_privateKey;
    @Value("${alipay.gateway}")
    private String gateway;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderSeervice orderService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/nativePayOrder")
    @ApiOperation("支付宝付款")
    public R nativePayOrder(@RequestBody PayOrderform form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        Integer orderId = form.getOrderId();
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(userId);
        QueryWrapper queryWrapper = new QueryWrapper(userEntity);
        int count = userService.count(queryWrapper);
        if (count == 0) {
            return R.error("用户不存在");
        }
        OrderEntity order = new OrderEntity();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        QueryWrapper queryWrapper1 = new QueryWrapper(order);
        int count1 = orderService.count(queryWrapper1);
        if (count1 == 0) {
            return R.error("不是有效的订单");
        }
        order = new OrderEntity();
        order.setId(orderId);
        QueryWrapper queryWrapper2 = new QueryWrapper(order);
        order = orderService.getOne(queryWrapper2);
        String amount = order.getAmount() + "";
        try {
            //调用支付宝的sdk
            AlipayClient client = new DefaultAlipayClient
                    (
                            gateway,
                            app_appId,
                            app_privateKey,
                            "json",
                            "UTF-8",
                            app_publicKey,
                            "RSA2"
                    );
            //设置支付宝的相关信息
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //设置返回的页面路径
            request.setReturnUrl("http://127.0.0.1:5500/mall/order.html");
            request.setNotifyUrl("http://www.zhifubao.com");
            String subject = "支付宝付款";
            String body = "支付宝付款";
            request.setBizContent("{\"out_trade_no\":\"" + order.getCode() + "\","
                    + "\"total_amount\":\"" + amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //发送支付订单的请求
            AlipayTradePagePayResponse response = client.pageExecute(request);
            //响应支付的结果
            String htmlCode = response.getBody();
            //响应中属性为success 支付成功
            if (response.isSuccess()) {
                //1 微信  2 支付宝 3 银联
                order.setPaymentType(2);
                order.setStatus(2);
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", order.getId());
                orderService.update(order, updateWrapper);
                return R.ok().put("htmlCode", htmlCode);
            } else {
                return R.error("创建订单失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("创建订单模块故障");
        }
    }

    @Login
    @PostMapping("/updateNativeOrderStatus")
    @ApiOperation("更新订单状态")
    public R updateNativeOrderStatus(@RequestBody UpdateNativeOrderStatusForm form, @RequestHeader HashMap header) {
        ValidatorUtils.validateEntity(form);
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        String code = form.getCode();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        orderEntity.setCode(code);
        QueryWrapper queryWrapper = new QueryWrapper(orderEntity);
        int count = orderService.count(queryWrapper);
        if (count == 0) {
            return R.error("用户与订单不匹配");
        }
        try {
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + orderEntity.getCode() + "\"," +
                    "    \"scene\":\"bar_code\"," +
                    "    \"auth_code\":\"" + form.getCode() + "\"," +
                    "    \"subject\":\"扫码付款测试\"," +
                    "    \"store_id\":\"NJ_001\"," +
                    "    \"timeout_express\":\"2m\"," +
                    "  }");
            AlipayTradeQueryResponse response = client.execute(request);
            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    UpdateWrapper updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("code", code);
                    updateWrapper.set("status", 2);
                    updateWrapper.set("payment_type", 2);
                    updateWrapper.set("prepay_id", response.getTradeNo());
                    orderService.update(updateWrapper);
                    return R.ok("订单状态已修改");
                } else {
                    return R.error("订单状态未修改");
                }
            }
            return R.error("订单状态未修改");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询支付订单失败");
        }
    }
}

